package gw.com.android.ui.onlive;

import android.Manifest;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.gwtsz.gts2.hx.R;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.presenter.http.HttpCallback;
import gw.com.android.presenter.http.MyConcernRequest;
import gw.com.android.terminal.AppTerminal;
import gw.com.android.ui.BaseActivity;
import gw.com.android.ui.dialog.SelectPhotoDialog;
import gw.com.android.ui.me.AlbumActivity;
import gw.com.android.ui.me.PhoneNumber;
import gw.com.android.ui.me.PreviewActivity;
import gw.com.android.ui.me_concern.AnalystData;
import gw.com.android.ui.views.PickImageView;
import gw.com.android.ui.views.PickedImageItem;
import gw.com.android.utils.ImageUtil;
import gw.com.android.utils.ThreadPool;
import www.com.library.util.NetworkMonitor;
import www.com.library.util.PermissionUtil;

/**
 * 添加晒单界面
 * Created by reeta.zou on 2017/5/17.
 */
public class DiscussAddActivity extends BaseActivity {

    public static final int REQUEST_PICK = 22;
    public static final int REQUEST_CAMERS = 23;
    public static final int REQUEST_PREVIEW = 24;
    private static final int MAX_IMAGE = 3;//可添加的图片最大数量
    private final List<String> images = new ArrayList<>(MAX_IMAGE);

    private static final int EDIT_MAX = 500;

    @BindView(R.id.add_content_edit)
    EditTextWithMaxLimit mContentEdit;
    @BindView(R.id.piv)
    PickImageView piv;
    @BindView(R.id.tv_count)
    TextView tv_count;
    private View guideView;


    private String takePhotoPath;
    private PermissionUtil mAccessCameraPermission;

    @Override
    protected int getLayoutView() {
        return R.layout.activity_home_discuss_add;
    }

    @Override
    protected void initLayoutView() {
        AppTerminal.instance().getMobileNumber();
        mTitleBar.setAppTitle(R.string.home_discuss_post_title);
        piv.setMaxCount(MAX_IMAGE);
        long guideCount = GTConfig.instance().getLongValue("add_discuss_image_count", 0);
        if (guideCount < 3) {
            guideView = findViewById(R.id.guide);
            guideView.setVisibility(View.VISIBLE);
            startGuideAnim();
            GTConfig.instance().setLongValue("add_discuss_image_count", ++guideCount);
        }
        mContentEdit.setMax(EDIT_MAX);
        tv_count.setText(0 + "/" + EDIT_MAX);
        mContentEdit.setTextWatcherCallback(new EditTextWithMaxLimit.TextWatcherCallback() {
            @Override
            public void onDataChange(int current) {
                tv_count.setText(current + "/" + EDIT_MAX);
            }
        });
    }

    @Override
    protected void initViewData() {
        piv.setOnPickImageListener(new PickImageView.OnPickImageListener() {
            @Override
            public void onAdd(PickImageView piv) {
                removeGuide();
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (null != mTitleBar.getWindowToken() && imm != null) {
                    imm.hideSoftInputFromWindow(mTitleBar.getWindowToken(), 0); //强制隐藏键盘
                }
                showSelectDialog(MAX_IMAGE - piv.currentSelected());
            }

            @Override
            public void onRemove(PickImageView piv, PickedImageItem item, String resrouce) {
                images.remove(resrouce);
            }

            @Override
            public void onPhoto(PickImageView piv, int index) {
                Intent intent = new Intent(DiscussAddActivity.this, PreviewActivity.class);
                intent.putStringArrayListExtra(PreviewActivity.IMAGE_PATH, new ArrayList<String>(images));
                intent.putExtra(PreviewActivity.IMAGE_INDEX, index);
                startActivityForResult(intent, REQUEST_PREVIEW);
            }
        });
        PhoneNumber.getInstance().acquireAsync(null);
    }

    private void startGuideAnim() {
        if (guideView == null) {
            return;
        }
        TranslateAnimation anim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0.1F, Animation.RELATIVE_TO_SELF, 0F);
        anim.setDuration(500);
        anim.setInterpolator(new DecelerateInterpolator());
        anim.setRepeatMode(Animation.REVERSE);
        anim.setRepeatCount(20);
        anim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                if (guideView == null) {
                    return;
                }
                ObjectAnimator alpha = ObjectAnimator.ofFloat(guideView, "alpha", 1, 0);
                alpha.setDuration(300);
                alpha.start();
                guideView = null;
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
        guideView.startAnimation(anim);
    }

    private void removeGuide() {
        if (guideView != null) {
            guideView.clearAnimation();
            ObjectAnimator alpha = ObjectAnimator.ofFloat(guideView, "alpha", 1, 0);
            alpha.setDuration(300);
            alpha.start();
            guideView = null;
        }
    }

    private void showSelectDialog(int currentSelected) {
        new SelectPhotoDialog(this, currentSelected).selectListener(new SelectPhotoDialog.OnSelectListener() {
            @Override
            public void onAlbum(SelectPhotoDialog dialog, View view) {
                album();
            }

            @Override
            public void onCamera(SelectPhotoDialog dialog, View view) {
                requestCameraPermission();
            }
        }).show();
    }

    private void album() {
        Intent intent = new Intent(getApplication(), AlbumActivity.class);
        intent.putStringArrayListExtra(AlbumActivity.PICKED_LIST, new ArrayList<>(images));
        startActivityForResult(intent, REQUEST_PICK);
    }

    private void requestCameraPermission() {
        mAccessCameraPermission = new PermissionUtil();
        mAccessCameraPermission.requestPermission(this, Manifest.permission.CAMERA, AppContances.REQUEST_PERMISSION_ACCESS_CAMERA, new PermissionUtil.OnRequestPermissionResult() {
            @Override
            public void onGranted() {
                launchCamera();
            }

            @Override
            public void onRefused() {
            }
        });
    }

    private void launchCamera() {
        try {
            takePhotoPath = ImageUtil.getNewPhotoPath();
            Intent mSourceIntent = ImageUtil.takeBigPicture(this, takePhotoPath);
            startActivityForResult(mSourceIntent, REQUEST_CAMERS);
        } catch (Exception ignore) {
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (mAccessCameraPermission != null) {
            mAccessCameraPermission.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @OnClick(R.id.tv_submit)
    void sendDiscuss() {

        //如果当前不是真实用户，则不允许发帖
        if (GTConfig.instance().getAccountType() != GTConfig.ACC_TYPE_REAL) {
            showToastPopWindow(AppMain.getAppString(R.string.home_discuss_not_real_2));
            return;
        }

        if (!NetworkMonitor.hasNetWork()) {
            return;
        }
        final String content = mContentEdit.getText().toString().trim();
        if (TextUtils.isEmpty(content)) {
            showToastPopWindow(AppMain.getAppString(R.string.home_discuss_add_content_null));
            return;
        }
        /*if (TextUtils.isEmpty(imageUrl)) {*/
        if (images.size() == 0) {
            showToastPopWindow(AppMain.getAppString(R.string.home_discuss_add_image_null));
            return;
        }
        showLoading();
        ThreadPool.getInstance().submit(new Runnable() {
            @Override
            public void run() {
//                realSend(content, false);
                getAllAnalyst(content);
            }
        });
    }

    private StringBuffer imgSize;//图片尺寸，多张图用 英文逗号分隔

    private void realSend(String content, boolean ifAnalyst, String analystNo) {
        imgSize = new StringBuffer();
        List<File> imagesUpload = new ArrayList<>(MAX_IMAGE);//循环压缩图片
        for (int i = 0; i < images.size(); i++) {
            final String targetPath = ImageUtil.getNewPhotoPath();
            final String compressImage = ImageUtil.compressImage(images.get(i), targetPath, 30, true);//调用压缩图片的方法，返回压缩后的图片path
            final File compressedPic = new File(compressImage);//被压缩成了一个本地的小图片文件
            imagesUpload.add(compressedPic);
            int[] wh = getWidthHeightOfImg(compressImage);
            imgSize.append(wh[0] + "*" + wh[1]);
            if (i < images.size() - 1)
                imgSize.append(",");
        }

        new DiscussAddRequest(content, ifAnalyst, analystNo, false, imagesUpload, new DiscussAddRequest.OnDiscussCallback() {
            @Override
            public void onSuccess() {
                hideLoading();
                showToastPopWindow(AppMain.getAppString(R.string.home_discuss_add_success));
                setResult(AppContances.RESULT_CODE);
                finish();
            }

            @Override
            public void onFailure() {
                hideLoading();
                showToastPopWindow(AppMain.getAppString(R.string.home_discuss_add_fail2));
            }
        }).execute(imgSize.toString());
    }

    // 封装方法，获取当前所有分析师
    private MyConcernRequest myConcernRequest;

    /**
     * 这里要插播一个步骤，判定当前用户是不是分析师,取出所有分析师，然后遍历,。。。野路子野路子
     *
     * @param content
     */
    private void getAllAnalyst(final String content) {
        if (myConcernRequest == null) {
            myConcernRequest = new MyConcernRequest();
        }
        myConcernRequest.getAllAnalystList(new HttpCallback<List<AnalystData>>() {
            @Override
            public void onSuccess(List<AnalystData> result) {
                // 获取成功之后，判断当前用户是不是

                String currentLoginPhone = GTConfig.instance().mCurLoginPhone;//手机号登录？
                String currentLoginName = GTConfig.instance().mCurName;//逐个对比，当前登录的用户名（可能是交易账户，可能是手机号码，现在只考虑交易账户） 和分析师的交易账户有没有相同的
                Log.d("currentLoginTag", currentLoginPhone + "-" + currentLoginName);

                String analystNo = "";
                boolean ifAnalyst = false;
                for (int i = 0; i < result.size(); i++) {
                    if (currentLoginName.equals(result.get(i).accountNo)) {// 一旦发现当前用户是分析师，那么直接发起 分析师发帖，isAnalyst为true
                        ifAnalyst = true;
                        analystNo = result.get(i).userNo;
                        break;
                    }
                }
                if (ifAnalyst)
                    Log.d("getAllAnalystTag2", "分析师大佬开始发帖");
                else
                    Log.d("getAllAnalystTag2", "普通用户开始发帖");

                realSend(content, ifAnalyst, TextUtils.isEmpty(analystNo) ? currentLoginPhone : analystNo);//普通用户没有分析师账号，所以要用手机号替代
            }

            @Override
            public void onFailure(Exception e) {
                Log.d("getAllAnalyst", "Exception:" + e.getLocalizedMessage());
            }
        });
    }

    public static int[] getWidthHeightOfImg(String srcPath) {
        int[] wh = new int[2];
        // 该对象为图片缩放操作对象
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        //开始读入图片，该参数为true时，只会在读取图片的宽高 而不产生bitmap 无论图片大小 都用他读取。
        newOpts.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(srcPath, newOpts);//此时返回bm为空
        //读取后一定要 设置成false;
        newOpts.inJustDecodeBounds = false;
        //获取 原图图片的长和宽
        int realw = newOpts.outWidth;
        int realh = newOpts.outHeight;
        wh[0] = realw;
        wh[1] = realh;
        Log.d("getWidthHeightOfImgTag", "" + realw + "-" + realh);
        return wh;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_PICK:
                if (data != null) {
                    images.clear();
                    piv.clear();
                    ArrayList<String> list = data.getStringArrayListExtra("result");
                    if (list != null && !list.isEmpty()) {
                        images.addAll(list);
                        piv.add(images);
                    }
                }
                break;
            case REQUEST_CAMERS:
                if (images.size() >= MAX_IMAGE) {
                    return;
                }
                if (TextUtils.isEmpty(takePhotoPath)) {
                    return;
                }
                images.add(takePhotoPath);
                piv.add(takePhotoPath);
                takePhotoPath = null;
                break;
            case REQUEST_PREVIEW:
                if (data != null) {
                    ArrayList<String> listT = data.getStringArrayListExtra("data");
                    if (listT != null && !listT.isEmpty()) {
                        images.removeAll(listT);
                        piv.remove(listT);
                    }
                }
            default:
                break;
        }
    }
}
